<template>

  <a-modal ref="modal" :title="calcTitle" :visible="visible" width="95%" @cancel="visible = false">
    <a-steps :current="current" size="small" v-if="operatorType === 'add' || operatorType === 'edit'">
      <a-step title="基础规则">1</a-step>
      <a-step title="其他规则"/>
      <a-step title="确认创建"/>
    </a-steps>
    <!-- 第一页 -->
    <template v-if="current === 0 || current === 2">
      <entity-view
        :operatorType="operatorType"
        :model="beanInfo"
        form-item-width="100%"
        :labelCol="{ span: 4 }"
        :wrapperCol="{ span: 8 }"
        :rules="firstStepRules"
        ref="firstStepForm"
      >
        <form-item label="营销活动名称" prop="mcName" v-model="beanInfo.mcName" :disabled="disabled"/>
        <form-item label="机构名称" prop="orgInfo">

          <a-tree-select
            :dropdownStyle="{maxHeight: '50vh'}"
            treeDataSimpleMode
            v-model="beanInfo.orgInfo"
            style="width: 100%"
            :tree-data="treeData"
            tree-checkable
            placeholder="请选择参与机构"
            :disabled="disabled"
            :showCheckedStrategy="SHOW_PARENT"
            :getPopupContainer="() => $refs.treeContainer"
            @change="setOrgInfo"
          />
          <div ref="treeContainer" style="position: relative;max-height: 300px;"/>
        </form-item>
        <form-item label="优惠方式" prop="mcMethod" :wrapperCol="{ span: 20 }">
          <a-radio-group name="mcMethod" v-model="beanInfo.mcMethod" :disabled="disabled" @change="changeMcMethod">
            <a-radio value="0">减免优惠</a-radio>
            <a-radio value="1">优惠券</a-radio>
          </a-radio-group>
          <br/>
          <template v-if="beanInfo.mcMethod === '0'">
            <a-radio-group v-model="beanInfo.mcType"
                           :disabled="disabled" name="mcType"
                           :options="[{label: '定额立减', value: '00'},{label: '随机立减', value: '01'},{label: '固定折扣立减', value: '02'},{label: '随机折扣立减', value: '03'}]"
                           @change="resetRuleInfoList"
            />
          </template>
          <template v-if="beanInfo.mcMethod === '1'">
            <a-radio-group name="mcType" v-model="beanInfo.mcType">
              <a-radio value="10">免费型</a-radio>
            </a-radio-group>
          </template>
        </form-item>
        <template v-if="beanInfo.mcMethod === '0' && beanInfo.mcType === '00'">
          <form-item
            :autoLink="false"
            :wrapperCol="{sm:{offset: 4}, xs:{offset:0}}"
            label="定额立减策略"
            style="width: 100%"
            prop="ruleInfoList"
          >
            <div v-for="(item,index) in beanInfo.ruleInfoList" :key="index">
              <span>满&nbsp;</span>
              <a-input-number :min="0" v-model="item.criteria" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;元, 减&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountFloor" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元, 共发放&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountQuantity" :max-length="9" :disabled="disabled"
                              :precision="0"/>
              <span>&nbsp;个, 单日消耗&nbsp;</span>
              <a-input-number :min="0" v-model="item.budgetDayLimit" :max-length="9" :disabled="disabled"
                              :precision="0"/>
              <span>&nbsp;个</span>
              <a href="javascript:" v-if="index!==0" @click="delRuleInfoListCol(index)">&nbsp;删除</a>
            </div>
          </form-item>
        </template>
        <template v-if="beanInfo.mcMethod === '0' && beanInfo.mcType === '01'">
          <form-item
            :autoLink="false"
            :wrapperCol="{sm:{offset: 4}, xs:{offset:0}}"
            label="随机立减策略"
            style="width: 100%"
            prop="ruleInfoList"
          >
            <div v-for="(item,index) in beanInfo.ruleInfoList" :key="index">
              <span>满&nbsp;</span>
              <a-input-number :min="0" v-model="item.criteria" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元, 减&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountFloor" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;至&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountCelling" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元, 预算&nbsp;</span>
              <a-input-number :min="0" v-model="item.budget" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元, 单日消耗上线&nbsp;</span>
              <a-input-number :min="0" v-model="item.budgetDayLimit" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元</span>
              <a href="javascript:" v-if="index!==0" @click="delRuleInfoListCol(index)">&nbsp;删除</a>
            </div>
          </form-item>
        </template>
        <template v-if="beanInfo.mcMethod === '0' && beanInfo.mcType === '02'">
          <form-item
            :autoLink="false"
            :wrapperCol="{sm:{offset: 4}, xs:{offset:0}}"
            label="固定折扣策略"
            style="width: 100%"
            prop="ruleInfoList"
          >
            <div v-for="(item,index) in beanInfo.ruleInfoList" :key="index">
              <span>满&nbsp;</span>
              <a-input-number :min="0" v-model="item.criteria" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;元, 打&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountFloor" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;折, 上限减&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountLimit" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元, 预算&nbsp;</span>
              <a-input-number :min="0" v-model="item.budget" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;元, 单日消耗上限&nbsp;</span>
              <a-input-number :min="0" v-model="item.budgetDayLimit" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元</span>
              <a href="javascript:" v-if="index!==0" @click="delRuleInfoListCol(index)">&nbsp;删除</a>
            </div>
          </form-item>
        </template>
        <template v-if="beanInfo.mcMethod === '0' && beanInfo.mcType === '03'">
          <form-item
            :autoLink="false"
            :wrapperCol="{sm:{offset: 4}, xs:{offset:0}}"
            label="随机折扣策略"
            style="width: 100%"
            prop="ruleInfoList"
          >
            <div v-for="(item,index) in beanInfo.ruleInfoList" :key="index">
              <span>满&nbsp;</span>
              <a-input-number :min="0" v-model="item.criteria" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;元, 打&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountFloor" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;至&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountCelling" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;折, 上限减&nbsp;</span>
              <a-input-number :min="0" v-model="item.discountLimit" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元, 预算&nbsp;</span>
              <a-input-number :min="0" v-model="item.budget" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;单日消耗上限&nbsp;</span>
              <a-input-number :min="0" v-model="item.budgetDayLimit" :max-length="9" :disabled="disabled"
                              :precision="2"/>
              <span>&nbsp;元</span>
              <a href="javascript:" v-if="index!==0" @click="delRuleInfoListCol(index)">&nbsp;删除</a>
            </div>
          </form-item>
        </template>
        <template v-if="beanInfo.mcMethod === '1' && beanInfo.mcType === '10'">
          <form-item
            inputType="select"
            label="领取渠道"
            v-model="beanInfo.claimChannelId"
            :options="[{label: '手机银行', value: '79'}]"
            optionsValue="value"
            optionsLabel="label"
            :wrapperCol="{span: 8}"
            prop="claimChannelId"/>
          <form-item
            :autoLink="false"
            :wrapperCol="{sm:{offset: 4}, xs:{offset:0}}"
            label="代金券策略"
            style="width: 100%"
            prop="couponRuleList"
          >
            <div v-for="(item,index) in beanInfo.couponRuleList" :key="index">
              <span>代金券面额&nbsp;</span>
              <a-input-number :min="0" v-model="item.denomination" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;元, 使用门槛: 订单金额满&nbsp;</span>
              <a-input-number :min="0" v-model="item.criteria" :max-length="9" :disabled="disabled" :precision="2"/>
              <span>&nbsp;元, 发放&nbsp;</span>
              <a-input-number :min="0" v-model="item.quantity" :max-length="9" :disabled="disabled" :precision="0"/>
              <span>&nbsp;张, 每日上限&nbsp;</span>
              <a-input-number :min="0" v-model="item.dayRedeemLimit" :max-length="9" :disabled="disabled"
                              :precision="0"/>
              <span>&nbsp;张</span>
              <a href="javascript:" v-if="index!==0" @click="delCouponRuleListCol(index)">&nbsp;删除</a>
            </div>
          </form-item>

        </template>
        <a-row type="flex" justify="center" style="width: 100%">
          <a-col span="16">
            <p style="color: red; font-weight: bold;">&nbsp;&nbsp;当前预算{{ budgetAmount }}元</p>
          </a-col>
          <a-col span="16">
            <a v-if="this.beanInfo.mcMethod === '0'"
               href="javascript:" @click="addRuleInfoListCol" :disabled="disabled">&nbsp;&nbsp;添加区间策略</a>
            <a v-if="this.beanInfo.mcMethod === '1'"
               href="javascript:" @click="addCouponRuleListCol" :disabled="disabled">&nbsp;&nbsp;添加区间策略</a>
          </a-col>
        </a-row>

        <form-item label="出资方式" :wrapperCol="{ span: 20 }" prop="sponsor" ref="sponsor">
          <a-radio-group
            :options="[{label: '银行全资', value: 0}, {label: '银行商户联合', value: 1}, {label: '商户全资免充值', value: 3}]"
            v-model="beanInfo.sponsor" :disabled="disabled"/>
          <!-- 银行商户联合 -->
          <div v-if="beanInfo.sponsor === 1">
            <p>若活动开始但未达到预计的商户数量，则银行资金有剩余</p>
            <span>银行出资金额&nbsp;</span>
            <a-input-number v-model="beanInfo.bankBudget" :min="0" :precision="2" :disabled="disabled"
                            @blur="() => {$refs.sponsor.onFieldBlur()}"/>
            <span>&nbsp;元,联合商户共出资{{ expectMchntQty }}元</span><br>
            <span>预期最多联合&nbsp;</span>
            <a-input-number v-model="beanInfo.expectedMcCount" :min="0" :precision="0" :disabled="disabled"/>
            <span>&nbsp;个商户,各商户出资{{
                mcFundingAmount
              }}元，各商户可用资金{{ mcAvailableAmount }}元(包括银行为其提供的{{ bankOfferedAmount }}元)</span>
          </div>
        </form-item>

        <form-item label="活动时间" prop="mcDateRange" ref="mcDateRange" :wrapperCol="{ span: 8 }">
          <a-range-picker
            v-model="beanInfo.mcDateRange"
            :allowClear="true"
            :disabled="disabled"
            style="max-width: 80%"
          />
          <a href="javascript:" v-if="current !== 2 && (operatorType === 'add' || operatorType === 'edit')"
             @click="setLongTime">&nbsp;长期</a>
        </form-item>

        <form-item label="可用时间" prop="mcTimeFlag" ref="mcTimeFlag" :wrapper-col="{span: 20}">
          <a-radio-group name="mcTimeFlag" v-model="beanInfo.mcTimeFlag" :disabled="disabled" @change="resetTimeList">
            <a-radio value="0">有效期内,任意时段可用</a-radio>
            <a-radio value="1">有效期内,部分时段可用</a-radio>
          </a-radio-group>
          <!-- 有效期内, 部分时段可用 -->
          <div v-if="beanInfo.mcTimeFlag === '1'">
            <a-checkbox-group v-model="beanInfo.availableWeekRange" name="availableWeekRange" :disabled="disabled">
              <a-checkbox v-for="option in weekRangeOptions" :key="option.value" :value="option.value">
                {{ option.label }}
              </a-checkbox>
            </a-checkbox-group>

            <div v-for="(item, index) in this.beanInfo.timeList" :key="index">
              <a-time-picker v-model="item.startTime" format="HH" @change="()=>$refs.mcTimeFlag.onFieldBlur()"
                             :disabled="disabled"/>
              <span>&nbsp;-&nbsp;</span>
              <a-time-picker v-model="item.endTime" format="HH" @change="()=>$refs.mcTimeFlag.onFieldBlur()"
                             :disabled="disabled"/>
              <a href="javascript:" v-if="index!==0" @click="delTimeList(index)"
                 :disabled="disabled">&nbsp;删除</a>
            </div>
          </div>
        </form-item>
        <a-row v-if="beanInfo.mcTimeFlag === '1'" type="flex" justify="center" style="width: 100%">
          <a-col span="16">
            <a @click="addTimeList" :disabled="disabled">添加时段</a>
          </a-col>
          <a-col span="16">
            <p>请按照24小时输入可用时刻, 最多设置三个时段</p>
          </a-col>
        </a-row>
        <!-- 代金券有效期 | 生效时间 -->
        <template v-if="beanInfo.mcMethod === '1' && beanInfo.mcType === '10'">
          <form-item label="代金券有效期" prop="couponDateFlag">
            <a-radio-group v-model="beanInfo.couponDateFlag" :disabled="disabled"
                           :options="[{label: '绝对日期范围', value: 0}, {label: '领劵后相对周期', value: 1}]"/>
            <div v-if="beanInfo.couponDateFlag === 0">
              <a-range-picker v-model="beanInfo.couponDateRange" :allowClear="true" :disabled="disabled"/>
            </div>
            <div v-if="beanInfo.couponDateFlag === 1">
              <span>领券后&nbsp;</span>
              <a-input-number :min="1" v-model="beanInfo.couponPeriod" :disabled="disabled"/>
              <span>&nbsp;个自然日失效</span>
            </div>
          </form-item>

          <form-item label="券生效时间" prop="availableDate">
            <span>券在领取&nbsp;</span>
            <a-select style="width: 120px" placeholder="请选择" v-model="beanInfo.availableDate" :disabled="disabled">
              <a-select-option value="0">立即生效</a-select-option>
              <a-select-option value="1">第二天生效</a-select-option>
            </a-select>
            <span>&nbsp;用户需在可用时间内使用</span>
          </form-item>
        </template>
      </entity-view>
    </template>
    <div class="hr" v-if="current === 2"></div>
    <!-- 第二页 -->
    <template v-if="current === 1 || current === 2">
      <entity-view
        :operatorType="operatorType"
        :model="beanInfo"
        form-item-width="100%"
        :labelCol="{ span: 4 }"
        :wrapper-col="{span: 8}"
        ref="secondStepForm"
        :rules="secondStepRules"
      >
        <form-item
          inputType="select"
          label="客户范围"
          v-model="beanInfo.clientRange"
          prop="clientRange"
          :options="[{name: '所有人', value: '0'}, {name: '指定用户', value: '1'}]"
          :disabled="disabled"/>
        <!-- 所有人 -->
        <form-item label="参与次数限制" prop="restriction" ref="restriction" :wrapperCol="{span: 18}">
          <span>活动期间每个用户可参与&nbsp;</span>
          <a-input-number :min="0" v-model="beanInfo.restriction" :max-length="9" size="small" :precision="0"
                          :disabled="disabled" @blur="() => { $refs.restriction.onFieldBlur() }"/>
          <span>&nbsp;次活动</span>
          <p class="tip">
            对于不能关联的多个银行卡、多个手机号、多个微信、支付宝、银联云闪付都各自按不同的用户计算！对于实际多个银行卡、多个手机号、多个微信、支付宝、银联云闪付同属于一个自然人且能够关联的按照同一个用户计算！</p>
        </form-item>

        <template v-if="beanInfo.clientRange === '1'">
          <form-item prop="consumerInfo" ref="consumerInfo" :wrapperCol="{span: 18, offset: 4}">
            <a-row class="child-item">
              <a-col span="12">
                <form-item label="手机号" :label-col="{span:4}" :wrapper-col="{ span: 20 }">
                  <div>
                    <a-textarea placeholder="请输入用户手机号" v-model="phoneText" :rows="2" style="width: 220px"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"/>
                    <a href="javascript:" :disabled="disabled" @click="handlePhoneText">&nbsp;确定</a>
                  </div>
                  <div style="line-height: 1.5em">
                    <div class="child-item-list" :style="{display: beanInfo.phoneList.length ? 'block':'none'}">
                      <div v-for="(phone, index) in beanInfo.phoneList" :key="index">
                        <a-space>
                          <span>{{ phone }}</span>
                          <a href="javascript:" :disabled="disabled" @click="delPhone(index)">&nbsp;删除</a>
                        </a-space>
                      </div>
                    </div>
                    <p>请输入手机号，一行一个，最多输入500个</p>
                    <p>已录入0个卡号</p>
                  </div>
                  <a-space>
                    <a href="javascript:" :disabled="disabled">导入</a>
                    <a href="javascript:" :disabled="disabled">点击下载导入模版</a>
                  </a-space>
                </form-item>
              </a-col>
              <a-col span="12">
                <form-item label="银行卡号" :label-col="{span:4}" :wrapper-col="{ span: 20 }">
                  <a-textarea placeholder="请输入用户银行卡号" v-model="bankCardText" :rows="2" style="width: 220px"
                              :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"/>
                  <a href="javascript:" :disabled="disabled" @click="handleBankCardText">&nbsp;确定</a>
                  <div style="line-height: 1.5em">
                    <div class="child-item-list" :style="{display: beanInfo.cardList.length ? 'block':'none'}">
                      <div v-for="(bankCard, index) in beanInfo.cardList" :key="index">
                        <span>{{ bankCard }}</span>
                        <a href="javascript:" :disabled="disabled" @click="delBankCard(index)">&nbsp;删除</a>
                      </div>
                    </div>
                    <p>请输入卡号，一行一个，最多输入500个</p>
                    <p>已录入0个卡号</p>
                  </div>
                  <a-space>
                    <a href="javascript:" :disabled="disabled">导入</a>
                    <a href="javascript:" :disabled="disabled">点击下载导入模版</a>
                  </a-space>
                </form-item>
              </a-col>
            </a-row>
            <div class="child-item">
              <a-table :columns="cardBinColumns" :data-source="beanInfo.kbinList" size="small" :scroll="{x: true}"
                       style="font-size: 12px" :pagination="{hideOnSinglePage: true}" class="card-bin-list">
                <a-input-number slot="cardBinNo" slot-scope="cardBin" v-model="cardBin.cardBin" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <a-input-number slot="dayCount" slot-scope="cardBin" v-model="cardBin.dayCount" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <a-input-number slot="weekCount" slot-scope="cardBin" v-model="cardBin.weekCount" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <a-input-number slot="monthCount" slot-scope="cardBin" v-model="cardBin.monthCount" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <a-input-number slot="quarterCount" slot-scope="cardBin" v-model="cardBin.quarterCount" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <a-input-number slot="yearCount" slot-scope="cardBin" v-model="cardBin.yearCount" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <a-input-number slot="currentCount" slot-scope="cardBin" v-model="cardBin.currentCount" size="small"
                                :disabled="disabled" @blur="$refs.consumerInfo.onFieldBlur()"
                                :min="1" :max="100000"/>
                <template v-slot:action>
                  <a href="javascript:;" :disabled="disabled" @click="delCardBinColumn">删除</a>
                </template>
              </a-table>
              <a-button type="link" @click="addCardBinColumn" :disabled="disabled">添加+</a-button>
            </div>
          </form-item>
        </template>

        <form-item label="商户范围" style="width:100%" :wrapper-col="{span:18}" prop="merchantRange" ref="merchantRange">
          <a-radio-group name="merchantRange" v-model="beanInfo.merchantRange" :disabled="disabled">
            <a-radio value="0">指定商户列表</a-radio>
            <a-radio value="1">商户上月日均存款达标</a-radio>
            <a-radio value="2">商户上月日均交易额达标</a-radio>
          </a-radio-group>
          <p class="tip">当前如果未选择任何商户或商圈，默认所选机构所有有效商户均自动参加当前营销活动</p>
          <template v-if="beanInfo.merchantRange === '0'">
            <div class="child-item">
              <merchant-selector ref="merchantSelector" v-model="beanInfo.merchantInfo"
                                 :checked-org-info="checkedOrgInfo" :disabled="disabled" @uploaded="templateUploaded"
                                 :hasUploaded="beanInfo.hasUploaded"></merchant-selector>
            </div>
            <div class="child-item">
              <a-row>
                <a-col :span="12" v-if="current !== 2">
                  <a-form-model-item label="商圈号" :wrapperCol="{ span: 24 }" labelAlign="left"
                                     prop="merchantCircleInfo">
                    <a-row type="flex" justify="space-between" align="bottom">
                      <a-col :span="19">
                        <a-textarea placeholder="请输入商圈编号" v-model="beanInfo.merchantCircleRows">
                        </a-textarea>
                      </a-col>
                      <a-col :span="4">
                        <a href="javascript:" @click="getBusinessArea">确定</a>
                      </a-col>
                    </a-row>
                    <div class="tip">
                      请输入商圈编号，一行一个，最多输入10个<br>
                      已录入{{ beanInfo.merchantCircleInfo.length }}个商圈
                    </div>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item label="商圈名称" :labelCol="{ span: 6 }" :wrapperCol="{ span: 24 }"
                                     labelAlign="left">
                    <a-row type="flex" justify="space-between"
                           v-for="(i, index) in beanInfo.merchantCircleInfo" :key="i.mchntNo">
                      <a-col :span="20">{{ i.mchntName }}({{ i.mchntNo }})</a-col>
                      <a-col :span="4" v-if="current !== 2"><a href="javascript:"
                                                               @click="deleteMerchantInfo('merchantCircleInfo', index)">删除</a>
                      </a-col>
                    </a-row>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </div>
          </template>
          <template v-if="beanInfo.merchantRange === '1' || beanInfo.merchantRange === '2'">
            <div class="child-item">
              <div v-if="beanInfo.merchantRange === '1'">
                <div>
                  <span>活动期间新增商户直接参与: </span>
                  <a-radio-group v-model="beanInfo.newMchntFlagDeposit" :disabled="disabled"
                                 :options="[{label: '否', value: '0'}, {label: '是', value: '1'}]"/>
                </div>
                <span>上月日均存款: </span>
                <a-input-number size="small" v-model="beanInfo.amtLimitFloorDeposit" :disabled="disabled"
                                placeholder="存款起始值" @blur="()=>{$refs.merchantRange.onFieldBlur()}"/>
                <span>&nbsp;-&nbsp;</span>
                <a-input-number size="small" v-model="beanInfo.amtLimitCellingDeposit" :disabled="disabled"
                                placeholder="存款结束值" @blur="()=>{$refs.merchantRange.onFieldBlur()}"/>
              </div>
              <div v-if="beanInfo.merchantRange === '2'">
                <div>
                  <span>活动期间新增商户直接参与: </span>
                  <a-radio-group v-model="beanInfo.newMchntFlagMoney" :disabled="disabled"
                                 :options="[{label: '否', value: '0'}, {label: '是', value: '1'}]"/>
                </div>
                <span>上月日均交易额: </span>
                <a-input-number size="small" v-model="beanInfo.amtLimitFloorMoney" :disabled="disabled"
                                placeholder="存款起始值" @blur="()=>{$refs.merchantRange.onFieldBlur()}"/>
                <span>&nbsp;-&nbsp;</span>
                <a-input-number size="small" v-model="beanInfo.amtLimitCellingMoney" :disabled="disabled"
                                placeholder="存款结束值" @blur="()=>{$refs.merchantRange.onFieldBlur()}"/>
              </div>
              <p style="font-size: 12px">活动开始系统自动选择满足条件商户，活动期间每月2号自动更新满足条件商户</p>
            </div>
          </template>
        </form-item>
        <!-- 线下 -->
        <a-form-model-item label="纳入营销的交易" prop="onLineProduce" :wrapper-col="{ span: 20 }" :autoLink="false"
                           ref="onLineProduce" :style="'width: 100%'" class="form-item">
          <div>线下</div>
          <div :style="{ borderBottom: '1px solid #E9E9E9' }">
            <a-checkbox :indeterminate="onLineIndeterminate" :checked="onLineCheckAll" @change="onLineCheckAllChange"
                        :disabled="disabled">全选
            </a-checkbox>
          </div>

          <a-checkbox-group v-model="beanInfo.onLineProduce" @change="onLineCheckboxChange" :disabled="disabled">
            <div class="label">刷卡支付：</div>
            <a-space>
              <a-checkbox value="MC001000">POS本行借记卡</a-checkbox>
              <a-checkbox value="MC001001">POS本行贷记卡</a-checkbox>
              <a-checkbox value="MC011000">POS本行贷记卡分期</a-checkbox>
              <a-checkbox value="MC001002">POS他行卡刷卡</a-checkbox>
            </a-space>
            <div class="label">二维码（客户被扫）：</div>
            <a-space>
              <a-checkbox value="MC021000">微信被扫</a-checkbox>
              <a-checkbox value="MC021010">支付宝被扫</a-checkbox>
              <a-checkbox value="MC021020">银联二维码被扫</a-checkbox>
            </a-space>
            <div class="label">二维码（客户主扫）：</div>
            <a-space>
              <a-checkbox value="PM003000">微信扫码支付</a-checkbox>
              <a-checkbox value="PM003010">支付宝扫码支付</a-checkbox>
              <a-checkbox value="PM003020">银联云闪付扫码支付</a-checkbox>
              <a-checkbox value="PM003030">手机银行APP扫码支付</a-checkbox>
            </a-space>
          </a-checkbox-group>

        </a-form-model-item>
        <!-- 线上 -->
        <a-form-model-item label="纳入营销的交易" prop="upLineProduce" :wrapper-col="{ span: 20 }" :autoLink="false"
                           ref="upLineProduce" :style="'width: 100%'" class="form-item">
          <div>线上</div>
          <div :style="{ borderBottom: '1px solid #E9E9E9' }">
            <a-checkbox :indeterminate="upLineIndeterminate" :checked="upLineCheckAll" @change="upLineCheckAllChange"
                        :disabled="disabled">
              全选
            </a-checkbox>
          </div>
          <a-checkbox-group v-model="beanInfo.upLineProduce" @change="upLineCheckboxChange" :disabled="disabled">
            <div class="label">微信APP：</div>
            <a-space>
              <a-checkbox value="PM002000">微信公众号支付</a-checkbox>
              <a-checkbox value="PM002010">微信小程序支付</a-checkbox>
              <a-checkbox value="PM002020">微信APP</a-checkbox>
            </a-space>
            <div class="label">二维码（客户主扫）：</div>
            <a-space>
              <a-checkbox value="PM003000">微信扫码支付</a-checkbox>
              <a-checkbox value="PM003010">支付宝扫码支付</a-checkbox>
              <a-checkbox value="PM003020">银联云闪付扫码支付</a-checkbox>
              <a-checkbox value="PM003030">手机银行APP扫码支付</a-checkbox>
            </a-space>
            <div class="label">本行借记卡快捷：</div>
            <a-space>
              <a-checkbox value="PM001000">新卡支付</a-checkbox>
              <a-checkbox value="PM011000">银行卡首次签约并支付</a-checkbox>
              <a-checkbox value="PM004000">本行卡快捷支付</a-checkbox>
            </a-space>
            <div class="label">本行贷记卡快捷：</div>
            <a-space>
              <a-checkbox value="PM001001">新卡支付</a-checkbox>
              <a-checkbox value="PM011001">银行卡首次签约并支付</a-checkbox>
              <a-checkbox value="PM004001">银联无卡快捷支付</a-checkbox>
            </a-space>

            <div class="label">他行卡快捷：</div>
            <a-space>
              <a-checkbox value="PM001002">新卡支付</a-checkbox>
              <a-checkbox value="PM011002">银行卡首次签约并支付</a-checkbox>
              <a-checkbox value="PM004012">>银联无跳转支付(后台接口)</a-checkbox>
              <a-checkbox value="PM004022">银联无卡快捷支付</a-checkbox>
            </a-space>

            <div class="label">本行手机银行APP：</div>
            <a-space>
              <a-checkbox value="PM005000">手机银行SDK支付</a-checkbox>
              <a-checkbox value="PM009000">手机银行银行卡+积分支付</a-checkbox>
            </a-space>
            <div class="label">银联云闪付三合一：</div>
            <a-space>
              <a-checkbox value="PM006000">银联云闪付支付</a-checkbox>
            </a-space>
            <div class="label">个人网关：</div>
            <a-space>
              <a-checkbox value="PM007000">本行个人网关支付</a-checkbox>
              <a-checkbox value="PM007020">他行个人网关支付</a-checkbox>
            </a-space>
            <div class="label">企业网关：</div>
            <a-space>
              <a-checkbox value="PM007010">本行企业网关支付</a-checkbox>
              <a-checkbox value="PM007030">他行企业网关支付</a-checkbox>
            </a-space>
            <div class="label">本行贷记卡分期：</div>
            <a-space>
              <a-checkbox value="PM010000">银行卡分期支付</a-checkbox>
              <a-checkbox value="PM012000">手机银行扫码分期支付</a-checkbox>
            </a-space>
          </a-checkbox-group>
        </a-form-model-item>
      </entity-view>
    </template>
    <!-- 发布页面显示的内容 -->
    <div class="hr"
         v-if="operatorType === 'release' ||operatorType === 'finish' || operatorType === 'examine' || operatorType === 'view'"/>
    <entity-view form-item-width='100%' :labelCol="{span:4}" :wrapperCol="{span:8}">
      <template v-if="operatorType === 'release'">
        <form-item label="付款帐号"/>
        <form-item label="发布意见" input-type="textarea"/>
      </template>
      <template v-if="operatorType === 'finish'">
        <form-item label="终止原因" input-type="textarea"/>
      </template>
      <template v-if="operatorType === 'view'">
        <form-item label="审核意见" input-type="textarea"/>
        <form-item label="发布意见" input-type="textarea"/>
      </template>
      <template v-if="operatorType === 'examine'">
        <form-item label="审核意见" input-type="textarea"/>
      </template>
    </entity-view>
    <!--操作-->
    <template v-slot:footer>
      <a-space ref="actions">
        <a-button v-if="current < 2" type="primary" @click="next">下一步</a-button>
        <a-button v-if="current === 2 && (operatorType === 'add' || operatorType === 'edit')"
                  type="primary" @click="submit">确认创建
        </a-button>
        <a-button v-if="current === 2 && (operatorType === 'add' || operatorType === 'edit')"
                  type="primary" @click="save(false)">保存草稿
        </a-button>
        <a-button v-if="current > 0 && (operatorType === 'add' || operatorType === 'edit')"
                  type="primary" @click="current-=1">返回
        </a-button>
        <a-button v-if="current === 2 && operatorType === 'release'"
                  type="primary">打款,发布
        </a-button>
        <a-button v-if="current === 2 && operatorType === 'release'"
                  type="primary">退回修改
        </a-button>
        <a-button v-if="current === 2 && operatorType === 'pause'"
                  type="primary">暂停
        </a-button>
        <a-button v-if="current === 2 && operatorType === 'finish'"
                  type="danger">强制终止
        </a-button>
        <a-button v-if="current === 2 && operatorType === 'play'"
                  type="primary">启用
        </a-button>
        <a-button v-if="current === 2 && operatorType === 'examine'" type="primary">通过</a-button>
        <a-button v-if="current === 2 && operatorType === 'examine'">退回</a-button>
        <a-button type="primary" @click="visible = false">关闭</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script>
import EntityView from "@/components/common/entityView/EntityView";
import FormItem from "@/components/common/entityView/FormItem";
import MerchantSelector from './MerchantSelector';
import {TreeSelect} from 'ant-design-vue';
import moment from 'moment';

const SHOW_PARENT = TreeSelect.SHOW_PARENT;
// 保留两位小数点
const floor = (number) => {
  if (typeof number !== 'number') {
    return NaN;
  }
  return Math.floor(number * 100) / 100;
}

let loadingLock = false;
let pIdCache = []
// getChildNodes和 getParentNodes 有可能影响性能，有待优化。
const getChildNodes = (nodes, treeObj) => {
  let childNodes = []
  nodes.forEach(node => {
    if (typeof node === 'string') {
      node = treeObj[node]
    }
    if (node && !pIdCache.includes(node.pId)) {
      const filterNodes = Object.values(treeObj).filter(i => i.pId === node.id)
      if (filterNodes.length) {
        childNodes.push(...filterNodes)
        pIdCache.push(node.id)
        childNodes.push(...getChildNodes(filterNodes, treeObj))
      }
    }
  })
  return childNodes
}
const getParentNodes = (nodes, treeObj) => {
  let parentNodes = []
  nodes.forEach(node => {
    if (typeof node === 'string') {
      node = treeObj[node]
    }
    if (node && node.pId && node.pId !== '999999999' && pIdCache.includes(node.pId) === false) {
      pIdCache.push(node.pId)
      const filterNodes = Object.values(treeObj).filter(i => i.id === node.pId)
      if (filterNodes.length) {
        parentNodes.push(...filterNodes)
        parentNodes.push(...getParentNodes(parentNodes, treeObj))
      }
    }
  })
  return parentNodes
}

const beanInfoInitData = {
  // 第一页的数据
  mcName: "", // 营销活动名称
  orgInfo: [], // 参与机构信息
  checkedOrgInfo: [], // 已选中的参与机构
  mcMethod: '0', // 优惠方式
  mcType: '00', // 优惠策略
  ruleInfoList: [{
    ruleIndex: '',
    criteria: '',
    discountFloor: '',
    discountCelling: '',
    discountQuantity: '',
    discountLimit: '',
    budget: '',
    budgetDayLimit: '',
    oprType: ''
  }],  // 区间策略
  couponRuleList: [],
  claimChannelId: '79',  // 领取渠道
  sponsor: 0,  // 出资方式
  bankBudget: '',  // 银行出资金额
  expectedMcCount: '',  // 预期商户数量
  mcDateRange: [], // 活动时间
  mcTimeFlag: '0',   // 可用时间
  availableWeekRange: [],  // 可用时间 部分时段可用 日期范围
  timeList: [],  // 可用时间 部分时间可用 时间范围
  couponDateFlag: 0, // 代金券有效期方式 0 绝对日期范围 1 领券后相对周期
  couponDateRange: [],  // 代金券绝对日期范围
  couponPeriod: '', // 代金券有限期相对周期
  availableDate: '0',  // 代金券生效日期

  // 第二页的数据
  clientRange: '0',   // 用户范围
  restriction: '',  // 参与次数限制
  phoneList: [],  // 可参加活动的手机号列表
  cardList: [],  // 可参加活动的银行卡号列表
  kbinList: [],  // 卡Bin
  merchantRange: '0',  // 商户范围
  merchantInfo: [], // 商户信息
  hasUploaded: false,
  merchantCircleRows: '',
  merchantCircleInfo: [], // 商圈信息
  newMchntFlagDeposit: '0', // 新增商户自动参加
  amtLimitFloorDeposit: '',
  amtLimitCellingDeposit: '',
  newMchntFlagMoney: '0',
  amtLimitFloorMoney: '',
  amtLimitCellingMoney: '',
  upLineProduce: [], // 纳入营销的交易 线下
  onLineProduce: [],  // 线上
}
const cardBinColumns = [
  {
    title: '卡BIN',
    scopedSlots: {customRender: 'cardBinNo'}
  },
  {
    title: '单日参与活动次数',
    scopedSlots: {customRender: 'dayCount'}
  },
  {
    title: '单周参与活动次数',
    scopedSlots: {customRender: 'weekCount'}
  },
  {
    title: '单月参与活动次数',
    scopedSlots: {customRender: 'monthCount'}
  },
  {
    title: '单季度参与活动次数',
    scopedSlots: {customRender: 'quarterCount'}
  },
  {
    title: '本年周参与活动次数',
    scopedSlots: {customRender: 'yearCount'}
  },
  {
    title: '本次参与活动次数',
    scopedSlots: {customRender: 'currentCount'}
  },
  {
    title: '操作',
    fixed: 'right',
    scopedSlots: {customRender: 'action'}
  },
]
const weekRangeOptions = [
  {label: '周一', value: 1},
  {label: '周二', value: 2},
  {label: '周三', value: 3},
  {label: '周四', value: 4},
  {label: '周五', value: 5},
  {label: '周六', value: 6},
  {label: '周日', value: 0}
]

export default {
  components: {
    EntityView,
    FormItem,
    MerchantSelector
  },
  data() {
    // 自定义校验器
    const checkMcDateRange = (rule, val, cb) => {
      if (!val || val.length === 0) {
        cb(new Error('请选择时间范围'));
      } else {
        cb();
      }
    }
    const checkRuleInfoList = (rule, val, cb) => {
      const {mcMethod, mcType, ruleInfoList} = this.beanInfo;
      for (let i = 0; i < ruleInfoList.length; i++) {
        if (mcMethod === '0') {
          // 减免优惠的校验
          let keys = null;
          if (mcType === '00') keys = ['criteria', 'discountFloor', 'discountQuantity', 'budgetDayLimit'];
          if (mcType === '01') keys = ['criteria', 'discountFloor', 'discountCelling', 'budget', 'budgetDayLimit'];
          if (mcType === '02') keys = ['criteria', 'discountFloor', 'discountLimit', 'budget', 'budgetDayLimit'];
          if (mcType === '03') keys = ['criteria', 'discountFloor', 'discountCelling', 'discountLimit', 'budget', 'budgetDayLimit'];

          keys.forEach((key) => {
            if (!ruleInfoList[i][key]) {
              cb(new Error(`请先完善第${i + 1}行的区间策略优惠信息!`));
              return;
            }
          });
          if (mcType === '00') {
            if (ruleInfoList[i]['criteria'] <= ruleInfoList[i]['discountFloor']) {
              cb(new Error(`第${i + 1}行的优惠区间策略活动门槛不能小于等于优惠力度！`));
              return;
            }
          }
          if (mcType === '01' || mcType === '03') {
            if (ruleInfoList[i]['discountFloor'] >= ruleInfoList[i]['discountCelling']) {
              cb(new Error(`第${i + 1}行的优惠区间策略优惠力度下限不能大于优惠力度上限！`));
              return;
            }
          }
        }
      }
      cb();
    }
    const checkCouponRuleList = (rule, val, cb) => {
      const {couponRuleList} = this.beanInfo
      const keys = ['denomination', 'criteria', 'quantity', 'dayRedeemLimit'];
      for (let i = 0; i < couponRuleList.length; i++) {
        if (keys.every(key => !couponRuleList[i][key])) {
          cb(new Error(`请先完善第${i + 1}行的代金券优惠信息!`));
          return;
        }
        if (couponRuleList[i]['denomination'] > couponRuleList[i]['criteria']) {
          cb(new Error(`第${i + 1}行的订单代金券面额不能大于满减金额!`));
          return;
        }
      }
      cb();
    }
    const checkSponsor = (rule, val, cb) => {
      cb();
    }
    const checkMcTimeFlag = (rule, val, cb) => {
      const {mcTimeFlag, availableWeekRange, timeList} = this.beanInfo;
      if (mcTimeFlag === '1') {
        if (availableWeekRange.length === 0) {
          cb(new Error('活动时间中的星期不能为空!'));
          return;
        }

        const len = timeList.length;
        for (let i = 0; i < len; i++) {
          const keys = Object.keys(timeList[i]);
          if (keys.some(key => !timeList[i][key])) {
            cb(new Error(`请先完善第${i + 1}行的时间段!`));
            return;
          }
          const timeRange = keys.map(key => {
            return timeList[i][key].format('HH');
          });
          if (timeRange[0] >= timeRange[1]) {
            cb(new Error(`第${i + 1}行的结束时段不能小于等于开始时段! `));
            return;
          }
          if (i >= 1) {
            const preTimeRage = keys.map(key => {
              return timeList[i - 1][key].format('HH');
            });
            if (timeRange[0] < preTimeRage[1]) {
              cb(new Error(`第${i + 1}行的开始时段应大于等于上一条结束时段! `));
              return;
            }
          }
        }
      }
      cb();
    }
    const checkCouponDateFlag = (rule, val, cb) => {
      if (this.beanInfo.couponDateFlag === 0) {
        if (this.beanInfo.couponDateRange.length === 0) {
          cb(new Error('代金券有效期的绝对日期不能为空!'));
          return;
        }
      }
      if (this.couponDateFlag === 1) {
        if (this.beanInfo.couponPeriod === '') {
          cb(new Error('代金券有效期的相对周期不能为空!'));
          return;
        }
      }
      cb();
    }
    const checkMerchantRange = (rule, val, cb) => {
      const {merchantRange} = this.beanInfo;
      if (merchantRange === '0') {
        if (!this.beanInfo.merchantInfo.length && !this.beanInfo.merchantCircleInfo.length && !this.beanInfo.hasUploaded) {
          cb(new Error(`请输入商户或商圈信息，或者使用导入功能`));
          return;
        }
      }
      if (merchantRange === '1') {
        const {dayDeposit} = this.beanInfo;
        if (!this.beanInfo.amtLimitFloorDeposit || !this.beanInfo.amtLimitCellingDeposit) {
          cb(new Error('请输入上月日均存款!'));
          return;
        }
        if (this.beanInfo.amtLimitFloorDeposit > this.beanInfo.amtLimitCellingDeposit) {
          cb(new Error('日均存款起始值不能大于结束值!'));
          return;
        }
      }
      if (merchantRange === '2') {
        const {dayExpense} = this.beanInfo;
        if (!this.beanInfo.amtLimitFloorMoney || !this.beanInfo.amtLimitCellingMoney) {
          cb(new Error('请输入上月日均交易额!'));
          return;
        }
        if (this.beanInfo.amtLimitFloorMoney > this.beanInfo.amtLimitCellingMoney) {
          cb(new Error('日均交易额起始值不能大于结束值!'));
          return;
        }
      }
      cb();
    }
    const checkCustomerInfo = (rule, val, cb) => {
      if (this.beanInfo.clientRange === '1') {
        const {phoneList, cardList, kbinList} = this.beanInfo;
        const phoneListLen = phoneList.length;
        const cardListLen = cardList.length;
        const kbinListLen = kbinList.length;
        if (phoneListLen === 0 && cardListLen === 0 && kbinListLen === 0) {
          cb(new Error('请输入手机号、银行卡卡号、卡BIN信息其中一项!'));
          return;
        }
        if ((phoneListLen !== 0 && cardListLen !== 0) || (phoneListLen !== 0 && kbinListLen !== 0)) {
          cb(new Error('手机号、银行卡卡号、卡BIN信息只能输入其中一项'));
          return;
        }
        if ((cardListLen !== 0 && kbinListLen !== 0) || (cardListLen !== 0 && kbinListLen !== 0)) {
          cb(new Error('手机号、银行卡卡号、卡BIN信息只能输入其中一项'));
          return;
        }
        for (let i = 0; i < kbinListLen; i++) {
          const keys = Object.keys(kbinList[i]);
          const res = keys.every(key => !!kbinList[i][key]);
          if (!res) {
            cb(new Error(`请完善第${i + 1}行的信息!`));
            return;
          }
        }
      }
      cb();
    }
    return {
      visible: false,  // 窗口显示隐藏
      operatorType: '', // 操作类型
      current: 1,
      beanInfo: Object.assign({}, beanInfoInitData),  // 数据来源
      SHOW_PARENT,
      SelectUserMode: '0', // 0: 所有人 1: 指定用户
      firstStepRules: { // 第一步校验规则
        mcName: [{required: true, message: "营销活动名称不能为空", trigger: "blur"}],
        orgInfo: [{required: true, trigger: "change", message: "请选择参与机构"}],
        mcMethod: [{required: true}],
        ruleInfoList: [{required: true, trigger: "blur", validator: checkRuleInfoList}],
        couponRuleList: [{required: true, trigger: "blur", validator: checkCouponRuleList}],
        mcDateRange: [{trigger: "blur", required: true, validator: checkMcDateRange}],
        sponsor: [{required: true}, {trigger: 'blur', validator: checkSponsor}],
        claimChannelId: [{required: true, message: "请选择领取渠道", trigger: "blur"}],
        mcTimeFlag: [{required: true}, {trigger: 'blur', validator: checkMcTimeFlag}],
        couponDateFlag: [{required: true}, {trigger: 'blur', validator: checkCouponDateFlag}],
        availableDate: [{required: true}]
      },
      secondStepRules: {
        clientRange: [{required: true, trigger: 'blur'}],
        restriction: [{required: true, message: '参与活动次数不能为空!'}],
        consumerInfo: [{trigger: 'blur', validator: checkCustomerInfo}],
        merchantRange: [{required: true}, {trigger: 'blur', validator: checkMerchantRange}],
        upLineProduce: [{required: true, message: "请勾选需要纳入营销的交易方式", trigger: "change"}],
        onLineProduce: [{required: true, message: "请勾选需要纳入营销的交易方式", trigger: "change"}],
      },
      weekRangeOptions,
      cardBinColumns,
      treeData: [],
      // 线上
      upLineIndeterminate: false,
      upLineCheckAll: false,
      upLineProduceList: [
        //微信APP
        'PM002000',
        'PM002010',
        'PM002020',
        //二维码（客户主扫）
        'PM003000',
        'PM003010',
        'PM003020',
        'PM003030',
        //本行借记卡快捷
        'PM001000',
        'PM011000',
        'PM004000',
        //本行贷记卡快捷
        'PM001001',
        'PM011001',
        'PM004001',
        //他行卡快捷
        'PM001002',
        'PM011002',
        'PM004012',
        'PM004022',
        //本行手机银行APP
        'PM005000',
        'PM009000',
        //银联云闪付三合一
        'PM006000',
        //个人网关
        'PM007000',
        'PM007020',
        //企业网关
        'PM007010',
        'PM007030',
        //本行贷记卡分期
        'PM010000',
        'PM012000',
      ],
      // 线下
      onLineIndeterminate: false,
      onLineCheckAll: false,
      onLineProduceList: [
        //刷卡支付
        'MC001000',
        'MC001001',
        'MC011000',
        'MC001002',
        //二维码（客户被扫）
        'MC021000',
        'MC021010',
        'MC021020',
        //二维码（客户主扫)
        'PM003000',
        'PM003010',
        'PM003020',
        'PM003030',
      ],
      bankCardText: '',
      phoneText: '',
      checkedOrgInfo: []
    }
  },
  methods: {
    show(beanInfo, operatorType) {
      this.visible = true;
      this.operatorType = operatorType;
      if (operatorType === 'add' || operatorType === 'edit') {
        this.current = 0;
        this.$nextTick(() => {
          this.$refs.firstStepForm.resetFields();
        });
      } else {
        this.current = 2;
      }
    },
    async initTreeData() {
      try {
        const res = await this.$get('/admin/market/cashierManager/getOrgList');
        this.treeData = (res.data || []).map(i => {
          i.id = i.orgCode
          i.orgId = i.orgCode
          i.value = i.orgCode
          i.label = i.orgName
          i.pId = i.superOrgCode
          return i
        });
        if (this.operatorType === 'edit' && this.visible) {
          this.setOrgInfo()
        }
      } catch (e) {
        this.$message.error('获取机构树失败');
      }
    },
    setOrgInfo() {
      if (Object.keys(this.treeObj).length) {
        // get child node
        let checkedNodes = this.beanInfo.orgInfo.map(i => this.treeObj[i]).filter(i => !!i)
        pIdCache = []
        checkedNodes = checkedNodes.concat(getChildNodes(this.beanInfo.orgInfo, this.treeObj))
        pIdCache = []
        checkedNodes = checkedNodes.concat(getParentNodes(this.beanInfo.orgInfo, this.treeObj))
        checkedNodes = Object.values(checkedNodes.reduce((item, next) => {
          item[next.id] = next
          return item
        }, {}))
        console.log('checkedNodes', checkedNodes)
        this.checkedOrgInfo = checkedNodes
      }
    },
    save() {
      this.submit(true);
    },
    async submit(isSave) {
      if (loadingLock) {
        this.$message.error('保存中，请勿重复点击');
        return
      }
      loadingLock = true
      const params = Object.assign({}, this.beanInfo);
      if (this.beanInfo.mcDateRange && this.beanInfo.mcDateRange.length === 2) {
        params['mcStartDate'] = this.beanInfo.mcDateRange[0];
        params['mcEndDate'] = this.beanInfo.mcDateRange[1];
      }
      if (this.beanInfo.couponDateRange && this.beanInfo.couponDateRange.length === 2) {
        params['couponStartDate'] = this.beanInfo.couponDateRange[0];
        params['couponEndDate'] = this.beanInfo.couponDateRange[1];
      }
      if (isSave) {
        // 存草稿
        params['oprType'] = '0';
        params['auditStatus'] = '00';
        params['mcStatus'] = '0';
      } else {
        params['oprType'] = '1';
        params['auditStatus'] = '01';
        params['mcStatus'] = '0';
      }
      if (params.orgInfo) {
        params.orgInfo = this.checkedOrgInfo;
      }
      params['merchantList'] = []; // 商户列表
      // 商户列表中添加oprType
      if (this.beanInfo.merchantInfo && this.beanInfo.merchantInfo.length) {
        params['merchantList'].push(...this.beanInfo.merchantInfo.map(i => {
          i.oprType = i.oprType || 'I'
          i.mchntType = '0'
          return i
        }))
      }
      // 商圈列表中添加oprType
      if (params.merchantCircleInfo) {
        params.merchantCircleInfo = this.beanInfo.merchantCircleInfo.map(i => {
          i.oprType = i.oprType || 'I'
          i.mchntType = '1'
          return i
        })
      }
      // 区间策略的参数必须为0，但是新建时默认的值是''
      params.ruleInfoList.forEach(ruleInfo => {
        const ruleInfoKeys = Object.keys(ruleInfo);
        if (ruleInfo['discountFloor'] !== '' && params.mcType !== '03') {
          ruleInfo['discountCelling'] = ruleInfo['discountFloor'];
        }
        ruleInfoKeys.forEach(key => ruleInfo[key] === '' ? ruleInfo[key] = 0 : ruleInfo[key]);
      })
      // 预算字段 budget
      params['budget'] = this.budgetAmount;
      console.log('提交新增请求', params);
      let hideLoading = this.$message.loading('提交中...', 0);
      try {
        const res = await this.$postJson('/admin/market/customerManager/add', params);
        if (res.data.code === '100000') {
          this.$message.success('保存成功');
          this.visible = false
          this.$emit('refresh');
        } else {
          this.$message.error("保存失败");
        }
      } catch (e) {
        console.log(e)
      }
      hideLoading && hideLoading();
      loadingLock = false;
    },
    changeMcMethod(e) {
      console.log(this.beanInfo.mcMethod)
      if (this.beanInfo.mcMethod === '0') {
        this.beanInfo.mcType = '00';
        this.resetRuleInfoList();
      }
      if (this.beanInfo.mcMethod === '1') {
        this.beanInfo.mcType = '10'
        this.resetCouponRuleList();
      }
    },
    deleteMerchantInfo(key, index) {
      this.$confirm({
        title: '提示',
        content: '确定删除该商户？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          this.beanInfo[key].splice(index, 1)
          this.$set(this.beanInfo, key, this.beanInfo[key])
        }
      })
    },
    resetRuleInfoList() {
      this.$nextTick(() => {
        this.beanInfo.ruleInfoList = [];
        this.beanInfo.couponRuleList = [];
        this.addRuleInfoListCol();
      })

    },
    resetCouponRuleList() {
      this.$nextTick(() => {
        this.beanInfo.ruleInfoList = [];
        this.beanInfo.couponRuleList = [];
        this.addCouponRuleListCol();
      })
    },
    // 添加区间策略
    addRuleInfoListCol() {
      this.$refs.firstStepForm.validateField('ruleInfoList', (errorMessage) => {
        if (!errorMessage) {
          this.beanInfo.ruleInfoList.push({
            ruleIndex: '',
            criteria: '',
            discountFloor: '',
            discountCelling: '',
            discountQuantity: '',
            discountLimit: '',
            budget: '',
            budgetDayLimit: '',
            oprType: ''
          });
        }
      })

    },
    // 删除区间策略
    delRuleInfoListCol(index) {
      this.beanInfo.ruleInfoList.splice(index, 1);
    },
    addCouponRuleListCol() {
      console.log('addCouponRuleListCol');
      this.$refs.firstStepForm.validateField('couponRuleList', (errorMessage) => {
        console.log('errorMessage', errorMessage)
        if (!errorMessage) {
          this.beanInfo.couponRuleList.push({
            rulIndex: '',
            criteria: '',
            denomination: '',
            quantity: '',
            dayRedeemLimit: '',
            purchaseFlag: '',
            purchaseAmt: '',
            batchTaskStatus: '',
            oprType: '',
          });
        }
      });
    },
    delCouponRuleListCol(index) {
      this.beanInfo.couponRuleList.splice(index, 1);
    },
    resetTimeList() {
      this.beanInfo.timeList = [];
      if (beanInfo.mcTimeFlag === '1') {
        this.addTimeList();
      }
    },
    // 添加可用时间的时段
    addTimeList() {
      this.$refs.firstStepForm.validateField('mcTimeFlag', (errorMessage) => {
        if (!errorMessage) {
          if (this.beanInfo.timeList.length < 3) {
            this.beanInfo.timeList.push({
              startTime: '',
              endTime: '',
            })
          } else {
            this.$message.error('最多添加三个时间段');
          }
        }
      })
    },
    // 删除可用时间的时段
    delTimeList(index) {
      this.beanInfo.timeList.splice(index, 1);
      this.$refs.mcTimeFlag.onFieldBlur();
    },
    // 添加一列卡Bin的数据
    addCardBinColumn() {
      const cardBinCol = {
        cardBin: '',
        dayCount: '',
        weekCount: '',
        monthCount: '',
        quarterCount: '',
        yearCount: '',
        currentCount: ''
      };
      const {phoneList, cardList, kbinList} = this.beanInfo;
      if (phoneList.length === 0 && cardList.length === 0) {
        if (kbinList.length === 0) {
          this.beanInfo.kbinList.push(cardBinCol);
        } else {
          this.$refs.secondStepForm.validateField('consumerInfo', (errorMessage) => {
            if (!errorMessage) {
              this.beanInfo.kbinList.push(cardBinCol);
            }
          });
        }
      } else {
        this.$refs.consumerInfo.onFieldBlur(); // 触发校验
      }

    },
    // 删除卡Bin的数据
    delCardBinColumn(index) {
      this.beanInfo.kbinList.splice(index, 1);
      this.$refs.consumerInfo.onFieldBlur(); // 触发校验
    },
    // 点击线上全选按钮
    upLineCheckAllChange(e) {
      Object.assign(this, {
        upLineIndeterminate: false,
        upLineCheckAll: e.target.checked,
      });
      this.$set(this.beanInfo, 'upLineProduce', e.target.checked ? this.upLineProduceList : []);
      this.$refs.upLineProduce.onFieldChange()
    },
    upLineCheckboxChange() {
      this.upLineIndeterminate = !!this.beanInfo.upLineProduce.length && this.beanInfo.upLineProduce.length < this.upLineProduceList.length;
      this.upLineCheckAll = this.beanInfo.upLineProduce.length === this.upLineProduceList.length;
      this.$refs.upLineProduce.onFieldChange()
    },
    // 点击线下全选按钮
    onLineCheckAllChange(e) {
      Object.assign(this, {
        onLineIndeterminate: false,
        onLineCheckAll: e.target.checked,
      });
      this.$set(this.beanInfo, 'onLineProduce', e.target.checked ? this.onLineProduceList : []);
      this.$refs.onLineProduce.onFieldChange()
    },
    onLineCheckboxChange() {
      this.onLineIndeterminate = !!this.beanInfo.onLineProduce.length && this.beanInfo.onLineProduce.length < this.onLineProduceList.length;
      this.onLineCheckAll = this.beanInfo.onLineProduce.length === this.onLineProduceList.length;
      this.$refs.upLineProduce.onFieldChange()
    },
    templateUploaded(fileUrl) {
      this.$set(this.beanInfo, 'hasUploaded', true);
      this.$set(this.beanInfo, 'mrctFilePath', fileUrl);
    },
    async getBusinessArea() {
      if (this.beanInfo.orgInfo.length === 0) {
        this.$message.error('请先选择参与机构');
        return
      }
      if (!this.beanInfo.merchantCircleRows || !this.beanInfo.merchantCircleRows.trim()) {
        this.$message.error('请输入商圈！');
        return
      }
      let merchantCircleList = this.beanInfo.merchantCircleRows.split('\n').filter(i => i.trim())
      if (merchantCircleList.length > 10) {
        this.$message.error('最多输入10个商户号！');
        return
      }
      // 去重
      merchantCircleList = [...new Set(merchantCircleList)]
      // 与之前输入的商户号对比去重
      let oldMerchantCircleList = this.beanInfo.merchantCircleInfo.map(i => i.mchntNo)
      merchantCircleList = merchantCircleList.filter(i => !oldMerchantCircleList.includes(i))
      if (merchantCircleList.length === 0) {
        this.$set(this.beanInfo, 'merchantCircleRows', '')
        this.$message.error('请输入新的商圈！');
        return
      }
      const hide = this.$message.loading('正在查询商圈信息...', 0);
      try {
        const res = await this.$postJson('/admin/market/cashierManager/getMcCircletList', {
          data: merchantCircleList.join(','),
          selectedOrgInfoList: this.checkedOrgInfo
        })
        if (res.data.code === '100000') {
          let successData = res.data.data.successData
          // 特殊费率的商户也可以添加
          const feeMchntObj = res.data.data.feeMchntData;
          successData = successData.concat(feeMchntObj);

          const errorData = res.data.data.errorData
          if (errorData.length > 0) {
            this.$notification.error({
              message: '提示',
              description: `录入的商圈/商户编号：${errorData.map(i => i.mchntNo).join(',')}存在错误，请重新输入！`,
              duration: 0
            });
          }
          const orgMchntData = res.data.data.orgMchntData;
          if (orgMchntData.length > 0) {
            this.$notification.error({
              message: '提示',
              description: `输入的商户或商圈内的商户所属的机构与已选的机构不符,${orgMchntData.map(i => i.mchntNo).join(',')}不符合要求，请重新输入！`,
              duration: 0
            });
          }
          if (successData.length) {
            this.$set(this.beanInfo, 'merchantCircleInfo', this.beanInfo.merchantCircleInfo.concat(successData))
          }
          this.$set(this.beanInfo, 'merchantCircleRows', '')
        } else {
          this.$message.error(res.data.message);
        }
      } catch (e) {
        this.$message.error('获取商户失败');
        console.error(e)
      }
      hide()
    },
    async next() {
      if (this.current === 0) {
        try {
          await this.$refs.firstStepForm.validate();
          this.current++;
        } catch (e) {
          console.log(e);
        }
      } else if (this.current === 1) {
        console.log(111);
        try {
          await this.$refs.secondStepForm.validate();
          this.current++;
        } catch (e) {
          console.log(e);
        }
      }
    },
    back() {
      this.current -= 1;
    },
    setLongTime() {
      this.$set(this.beanInfo, 'mcDateRange', [moment().format('YYYY-MM-DD'), moment(new Date('2099/12/31')).format('YYYY-MM-DD')]);
      this.$refs.mcDateRange.onFieldBlur()
    },
    handleBankCardText() {
      const {cardList} = this.beanInfo
      const reg = /^([1-9])(\d{15}|\d{16}|\d{18})$/;
      // 这里需要去重和校验银行卡号正确性
      let newBankCardList = this.bankCardText.split('\n').filter(phone => reg.test(phone));
      this.$set(this.beanInfo, 'cardList', [...new Set(newBankCardList.concat(cardList))]);
      this.$refs.consumerInfo.onFieldBlur();  // 触发校验
    },
    handlePhoneText() {
      const {phoneList} = this.beanInfo;
      const reg = /^1[3-9]\d{9}$/;
      // 校验手机号和去重
      let newPhoneList = this.phoneText.split('\n').filter(phone => reg.test(phone));
      this.$set(this.beanInfo, 'phoneList', [...new Set(newPhoneList.concat(phoneList))]);
      this.$refs.consumerInfo.onFieldBlur(); // 触发校验
    },
    delPhone(index) {
      this.beanInfo.phoneList.splice(index, 1);
      this.$refs.consumerInfo.onFieldBlur(); // 触发校验
    },
    delBankCard(index) {
      this.beanInfo.cardList.splice(index, 1);
      this.$refs.consumerInfo.onFieldBlur(); // 触发校验
    }
  },
  computed: {
    disabled() {
      return this.current === 2
    },
    // 计算弹出层的标题
    calcTitle() {
      let title = "客户营销活动";
      switch (this.operatorType) {
        case 'add':
          title = '新增' + title;
          break;
        case 'edit':
          title = '编辑' + title;
          break;
        case 'view':
          title = '查看' + title;
          break;
        case 'release':
          title = '发布' + title;
          break;
        case 'pause':
          title = '暂停' + title;
          break;
        case 'finish':
          title = '终止' + title;
          break;
        case 'play':
          title = '启用' + title;
          break;
        case 'examine':
          title = '审核' + title
      }
      return title

    },
    treeObj() {
      return this.treeData.reduce((i, next) => {
        i[next.id] = next
        return i
      }, {})
    },
    // 计算预算金额
    budgetAmount() {
      const {mcMethod, mcType} = this.beanInfo;
      console.log(mcMethod, mcType);
      // 定额立减策略
      if (mcMethod === '0') {
        if (mcType === '00') {
          return this.beanInfo.ruleInfoList.reduce((total, cur) => {
            if (cur.discountFloor && cur.discountQuantity) {
              return total += (cur.discountLimit * cur.discountQuantity);
            } else {
              return total;
            }
          }, 0)
        } else {
          return this.beanInfo.ruleInfoList.reduce((total, cur) => {
            if (cur.budget) {
              return total += cur.budget;
            } else {
              return total;
            }
          }, 0)
        }
      }
      console.log('代金券');
      // 代金券策略
      if (mcMethod === '1' && mcType === '10') {
        return this.beanInfo.ruleInfoList.reduce((total, cur) => {
          if (cur.denomination && cur.quantity) {
            return total += (cur.denomination * cur.quantity);
          } else {
            return total;
          }
        }, 0);
      }
      return 0
    },
    // 计算商户共出资金额
    expectMchntQty() {
      const budgetAmount = this.budgetAmount;
      const bankBudget = this.beanInfo.bankBudget;
      if (budgetAmount && !bankBudget) {
        return budgetAmount
      }
      if (budgetAmount < bankBudget) {
        return 0
      } else {
        return floor(budgetAmount - bankBudget);
      }
    },
    // 计算每个商户的出资金额
    mcFundingAmount() {
      const expectMchntQty = this.expectMchntQty;  // 商户共出资
      const expectedMcCount = this.beanInfo.expectedMcCount;  // 预期商户数量
      if (expectMchntQty && expectedMcCount) {
        return floor(expectMchntQty / expectedMcCount);
      }
      return 0;
    },
    // 计算银行提供的分给各个商户的资金
    bankOfferedAmount() {
      const bankBudget = this.beanInfo.bankBudget; // 银行提供资金
      const expectedMcCount = this.beanInfo.expectedMcCount; // 预期商户数量
      if (bankBudget && expectedMcCount) {
        return floor(bankBudget / expectedMcCount);
      }
      return 0;
    },
    // 计算每个商户的可用金额
    mcAvailableAmount() {
      const mcFundingAmount = this.mcFundingAmount; // 各商户提供资金
      const bankOfferedAmount = this.bankOfferedAmount; // 银行提供给各商户的资金
      return floor(Number(mcFundingAmount) + Number(bankOfferedAmount));
    }
  },
  mounted() {
    this.initTreeData();
  }
}
</script>

<style scoped>
.child-item {
  background: #F7F8FA;
  border: 1px solid #E0E0E0;
  padding: 20px;
  border-radius: 2px;
  margin: 20px 0;
}

.tip {
  color: red;
  line-height: 1.5em;
  font-size: 12px;
}

p {
  margin: 0;
}

.ant-table-wrapper /deep/ .ant-table-body {
  font-size: 10px;
}

.label {
  margin: 20px 0 10px;
}

.hr {
  width: 100%;
  height: 1px;
  background: #E0E0E0;
  margin: 10px 0;
}

.card-bin-list /deep/ .ant-table-placeholder {
  display: none;
}

.child-item-list {
  max-height: 60px;
  overflow: auto;
  max-width: 220px;
  width: 100%;
  border: 1px solid #eee;
}
</style>
